<template>
    <div>
        <h2>人脸比对</h2>
        <input v-model="phone" placeholder="请输入用户名" />
        <button @click="captureAndCompare">比对</button>
        <!-- 显示视频流 -->
        <video ref="video" autoplay></video>
        <!-- 显示画布 -->
        <canvas ref="canvas" style="display: none;"></canvas>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import axios from 'axios';
// import http from '../http';

// 存储用户名
const phone = ref('');
// 视频元素引用
const video = ref<HTMLVideoElement | null>(null);
// 画布元素引用
const canvas = ref<HTMLCanvasElement | null>(null);
// 从本地存储中获取的 OSS 图片 URL
const ossImageUrl = ref<string>('');

// 当组件挂载时，初始化摄像头获取视频流并从本地存储中获取图片 URL
onMounted(() => {
    initCamera();
    fetchOssImageFromLocalStorage(); // 获取 OSS 图片 URL
});

// 当组件卸载前，关闭摄像头视频流
onBeforeUnmount(() => {
    stopCamera();
});

// 初始化摄像头，获取视频流
const initCamera = async () => {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        video.value!.srcObject = stream;
        video.value!.play();
    } catch (error) {
        console.error('初始化摄像头出错：', error);
    }
};

// 停止摄像头视频流
const stopCamera = () => {
    if (video.value && video.value.srcObject) {
        const tracks = (video.value.srcObject as MediaStream).getTracks();
        tracks.forEach((track) => track.stop());
    }
};

// 从本地存储中获取 OSS 图片 URL
const fetchOssImageFromLocalStorage = () => {
    const storedUrl = localStorage.getItem('file_url'); // 假设存储的键为 "ossImageUrl"
    if (storedUrl) {
        ossImageUrl.value = storedUrl;
        console.log('从本地存储获取到的 OSS 图片 URL:', ossImageUrl.value);
    } else {
        alert('未找到本地存储中的 OSS 图片 URL');
    }
};

// 捕获人脸图像并进行比对操作
const captureAndCompare = async () => {
    try {
        if (!ossImageUrl.value) {
            alert('OSS 图片 URL 不存在，请检查本地存储');
            return;
        }

        // 等待视频流稳定，可根据实际情况调整等待时间
        await new Promise((resolve) => setTimeout(resolve, 1000));

        canvas.value!.width = video.value!.videoWidth;
        canvas.value!.height = video.value!.videoHeight;
        const ctx = canvas.value!.getContext('2d');
        if (ctx) {
            ctx.drawImage(video.value!, 0, 0, canvas.value!.width, canvas.value!.height);
            // 将画布内容转换为 Base64 编码的图片
            const videoImageData = canvas.value!.toDataURL('image/jpeg');
            const videoBase64 = videoImageData.split(',')[1];
            // 显示在画布上
            canvas.value!.style.display = 'block';
            // 构造表单数据
            const formData = new FormData();
            formData.append('img1_url', ossImageUrl.value); // 从本地存储获取的 OSS 图片 URL
            formData.append('img2', videoBase64); // 视频截图 Base64 数据

            // 调用后端接口上传图片并进行比对
            const response = await axios.post('http://127.0.0.1:8000/user/face/', formData);
            console.log('人脸比对结果：', response.data);
            if (response.data.code === 200) {

                alert('比对结果：' + response.data.msg);
            } else {
                alert('比对失败：' + response.data.msg);
            }
        }
    } catch (error) {
        console.error('人脸比对出错：', error);
    } finally {
        stopCamera();
    }
};
</script>

<style>
video {
    width: 100%;
    height: auto;
}

canvas {
    width: 100%;
    height: auto;
    border: 1px solid #000;
}
</style>